package com.athl.gulimall.product.service.impl;

import com.athl.common.exception.RRException;
import com.athl.common.utils.PageUtils;
import com.athl.common.utils.Query;
import com.athl.gulimall.product.dao.CategoryDao;
import com.athl.gulimall.product.entity.CategoryEntity;
import com.athl.gulimall.product.service.CategoryBrandRelationService;
import com.athl.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 树型显示
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组成夫子树的树形结构

        //2.1) 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity->
             categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu1.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
//        List<CategoryEntity> treeMenus = categoryEntities.stream().filter((categoryEntity) -> {
//            return categoryEntity.getParentCid() == 0;
//        }).sorted((menu1, menu2) -> {
//            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
//        }).map((menu) -> {
//            menu.setChildren(getChildren(menu, categoryEntities));
//            return menu;
//        }).collect(Collectors.toList());
//
//        return treeMenus;
        return level1Menus;
    }
    //递归查找虽有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1.找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2.菜单的排序
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu1.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

//    private List<CategoryEntity> getChildren(CategoryEntity rootMenu, List<CategoryEntity> allMenus) {
//
//        List<CategoryEntity> childrenList = allMenus.stream().filter(categoryEntity -> {
//            return categoryEntity.getParentCid().equals(rootMenu.getCatId());
//        }).map(menu  -> {
//            menu.setChildren(getChildren(menu, allMenus));
//            return menu;
//        }).sorted((m1, m2) -> {
//            return (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort());
//        }).collect(Collectors.toList());
//        return childrenList;
//    }

    @Override
    public void removeMenus(List<Long> asList) {
        System.out.println("删除的数据为： ++ ++++" + asList);
        // 逻辑删除
        int result = baseMapper.deleteBatchIds(asList);
        if (result < 0) {
            throw new RRException("删除失败");
        }
    }

    /**
     * 寻找一个category的全路径  example [2.3,6]
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCategoryPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, path);
        //父节点add到了最后  真是需要的时候是需要逆序的
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }


    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单， 是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);

    }


    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    private List<Long> findParentPath(Long catelogId, List<Long> path) {
        path.add(catelogId);
        CategoryEntity categoryEntity = baseMapper.selectById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), path);
        }
        return path;
    }
}